package com.gexiaobao.pigeon.ui.fragment.mine.training

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.text.format.DateFormat
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import com.bin.david.form.core.SmartTable
import com.bin.david.form.core.TableConfig
import com.bin.david.form.data.CellInfo
import com.bin.david.form.data.format.bg.BaseCellBackgroundFormat
import com.bin.david.form.data.style.FontStyle
import com.bin.david.form.data.style.LineStyle
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.DailyScanResponse
import com.gexiaobao.pigeon.app.network.ListDataUiState
import com.gexiaobao.pigeon.app.util.DatetimeUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.FragmentDailyScanBinding
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.MyTrainingViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 18:20
 * @Describe    : 每日扫描
 */
class FragmentDailyScan : BaseFragment<MyTrainingViewModel, FragmentDailyScanBinding>() {

    private var currentDate: String = ""
    private var fosterName: String = ""
    lateinit var data: SmartTable<DailyScanResponse.DataList>
    private lateinit var dialog: RxDialogDefault

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mDatabind.toolBar.toolbar.initClose(getString(R.string.daily_scan)) {
            nav().navigateUp()
        }
        mDatabind.toolBar.tvRightMenu.text = getString(R.string.reset)
        mDatabind.toolBar.tvRightMenu.background = context?.resources!!.getDrawable(R.drawable.round_tv_red_stroke20_bg)
        currentDate = DateFormat.format("yyyy-MM-dd", System.currentTimeMillis()) as String
        mViewModel.pickDateText.set(currentDate)

        mDatabind.etSearch.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH ->
                    searchData()

                else -> {}
            }
            false
        }
    }

    private fun searchData() {
        hideSoftKeyboard(activity)
        when {
            mViewModel.searchName.get().isEmpty() -> showMessage(getString(R.string.enter_the_name_of_the_foster_carer_you_want_to_inquire_about))
            else -> {
                refreshData(true)
            }
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        refreshData(true)
    }

    override fun initData() {
        super.initData()
        initSmartTable()

        mDatabind.swipeRefreshLayout.init {
            currentDate = mViewModel.pickDateText.get()
            refreshData(true)
        }

        mDatabind.etSearch.addTextChangedListener {
            if (it!!.isEmpty()) {
                currentDate = mViewModel.pickDateText.get()
                fosterName = ""
                refreshData(true)
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.llChooseTime, mDatabind.tvSearch, mDatabind.toolBar.tvRightMenu) {
            when (it) {
                mDatabind.llChooseTime -> {
                    chooseDate()
                }

                mDatabind.tvSearch -> {
                    currentDate = mViewModel.pickDateText.get()
                    fosterName = mViewModel.searchName.get()
                    refreshData(true)
                }

                mDatabind.toolBar.tvRightMenu -> {
                    showCleanScanDialog()
                }
            }
        }
    }

    private fun showCleanScanDialog() {
        dialog = RxDialogDefault(context)
        dialog.setTitle(getString(R.string.is_reset_scan_daily))
        dialog.setRightBtnContent(getString(R.string.sure))
        dialog.setLeftBtnContent(getString(R.string.cancel))
        dialog.setSureListener {
            dialog.dismiss()
        }
        dialog.setCancelListener {
            showLoading(getString(R.string.loading))
            mViewModel.clearDailyScan()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun chooseDate() {
        val displayList: MutableList<Int> = mutableListOf()
        displayList.add(DateTimeConfig.YEAR)
        displayList.add(DateTimeConfig.MONTH)
        displayList.add(DateTimeConfig.DAY)
        val dialog = context?.let { it ->
            CardDatePickerDialog.builder(it)
                .setTitle(getString(R.string.option_date))
                .setDisplayType(displayList)
                .setBackGroundModel(CardDatePickerDialog.STACK)
                .showBackNow(false)//是否显示一键回到今日 和 定位到今天的日期
//                .setMaxTime(maxDate)
                .setPickerLayout(0)
//                .setMinTime(minDate)
//                .setDefaultTime(defaultDate)
                .setTouchHideable(true)
                .setChooseDateModel(DateTimeConfig.DATE_LUNAR)
                .setWrapSelectorWheel(false)
                .setThemeColor(Color.parseColor("#FF8000"))
//                .setAssistColor(Color.parseColor("#DDFFFFFF"))
//                .setDividerColor(Color.parseColor("#222222"))
                .showDateLabel(false)
                .showFocusDateInfo(false)
                .setOnChoose(getString(R.string.select)) {
                    mViewModel.pickDateText.set(DatetimeUtil.conversionTime(it, "yyyy-MM-dd"))
                    currentDate = mViewModel.pickDateText.get()
                    refreshData(true)
                }
                .setOnCancel(getString(R.string.closed)) {
                }.build()
        }
        dialog?.show()
        //重点 需要在dialog show 方法后
        //得到 BottomSheetDialog 实体，设置其 isHideable 为 fasle
        (dialog as BottomSheetDialog).behavior.isHideable = false
    }

    private fun initSmartTable() {
        data = mDatabind.smartTable as SmartTable<DailyScanResponse.DataList>
        val fontStyle = context?.let { ContextCompat.getColor(it, R.color.black) }?.let { FontStyle(context, 18, it) }
        val contentStyle = context?.let { ContextCompat.getColor(it, R.color.comm_text_gray) }?.let { FontStyle(context, 16, it) }
        val lineStyle = LineStyle()
        lineStyle.color = context?.let { ContextCompat.getColor(it, R.color.dedede) }!!
        data.config.columnTitleStyle = fontStyle
        data.config.contentStyle = contentStyle
        data.config.setHorizontalPadding(20)
            .setVerticalPadding(40)
            .setSequenceHorizontalPadding(20)
            .setSequenceVerticalPadding(40)
            .setShowTableTitle(false) // 去除标题
            .setFixedFirstColumn(true) //第一行作废
            .setShowXSequence(false)
            .setShowYSequence(false)
            .isFixedYSequence = true
    }

    override fun createObserver() {
        super.createObserver()
        /** 重置每日扫描 */
        mViewModel.cleanDailyScanResult.observe(viewLifecycleOwner) {
            if (::dialog.isInitialized) {
                dialog.dismiss()
            }
            if (it.isSuccess) {
                refreshData(true)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 每日扫描结果 */
        mViewModel.dailyScanListResult.observe(viewLifecycleOwner) {
            if (mDatabind.swipeRefreshLayout.isRefreshing) {
                mDatabind.swipeRefreshLayout.isRefreshing = false
            }
            dismissLoading()
            if (it.isEmpty) {
                mDatabind.smartTable.visibility = View.GONE
            } else {
                mDatabind.smartTable.visibility = View.VISIBLE
                setSmartTableData(it)
            }
        }
    }

    private fun setSmartTableData(it: ListDataUiState<DailyScanResponse.DataList>?) {
        val listData = ArrayList<DailyScanResponse.DataList>()
        if (it != null) {
            it.listData?.forEachIndexed { index, resultList ->
                listData.add(index, resultList)
                if (!TextUtils.isEmpty(resultList.ringId)) {
                    val split = resultList.ringId.split("-")
                    if (split.size == 3) {
                        resultList.ringId = "${split[0]}-${split[1]}-\n${split[2]}"
                    }
                }
                if (!TextUtils.isEmpty(resultList.scanTime)) {
                    resultList.scanTime = resultList.scanTime.replace(" ", "\n")
                }
                if (resultList.scanTime.isEmpty()) {
                    resultList.scanTime = getString(R.string.daily_no_scan)
                }

                resultList.serialNumber = index + 1

                var eyeStr = ""
                when (it.listData[index].eyePattern) {
                    1 -> {
                        eyeStr = getString(R.string.hint_unknown)
                    }

                    2 -> {
                        eyeStr = getString(R.string.pigeon_yellow)
                    }

                    3 -> {
                        eyeStr = getString(R.string.pigeon_sha)
                    }

                    4 -> {
                        eyeStr = getString(R.string.pigeon_bull)
                    }
                }
                resultList.eyePatternStr = eyeStr

                var sexStr = ""
                when (it.listData[index].sex) {
                    1 -> {
                        sexStr = getString(R.string.hint_unknown)
                    }

                    2 -> {
                        sexStr = getString(R.string.hint_female)
                    }

                    3 -> {
                        sexStr = getString(R.string.hint_male)
                    }
                }
                resultList.sexStr = sexStr

            }
            data.setData(listData)

            data.config.contentCellBackgroundFormat = object : BaseCellBackgroundFormat<CellInfo<*>>() {

                override fun getTextColor(t: CellInfo<*>): Int {
                    return if ("寄养人" == t.column.columnName) {
                        ContextCompat.getColor(context!!, R.color.bg_light_bllue)
                    } else {
                        super.getTextColor(t)
                    }
                }

                override fun getBackGroundColor(t: CellInfo<*>?): Int {
                    return TableConfig.INVALID_COLOR
                }
            }

            data.tableData?.setOnItemClickListener { column, _, t, _, _ ->
                if ("寄养人" == column.columnName) {
                    if (t != null) {
                        if (!TextUtils.isEmpty(t.toString())) {
                            fosterName = t.toString()
                            mViewModel.searchName.set(fosterName)
                            currentDate = mViewModel.pickDateText.get()
                            refreshData(true)
                        }
                    }
                }
            }
        }
    }

    private fun refreshData(b: Boolean) {
        showLoading(getString(R.string.loading))
        mViewModel.getScanDetail(b, currentDate, fosterName)
    }
}